package cn.pconline.autoclub.web;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.exception.ApiException;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.AppUtils;
import cn.pconline.autoclub.util.WebUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.gelivable.dao.GeliDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author zhouruxuan
 * @date 2014年8月27日 下午3:57:48
 */
@Controller
public class TokenController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private GeliDao geliDao;
	@Autowired
	SystemConfig systemConfig;
	@Autowired
	private ClubService clubService;
	@Autowired
	private UserAuth userAuth;
	
	private static final Logger log = LoggerFactory
			.getLogger(TokenController.class);

	// 融云服务器信息
	private static URL AUTH_URL;
	private static final int INVALID_USER_CODE = 1;
	private static final String INVALID_USER = "非登录用户!";
	private static final int NOT_CLUB_MEMBER_CODE = 2;
	private static final String NOT_CLUB_MEMBER = "此用户不是车友会成员！";
	private static final int FAIL_TOKEN_CODE = 3;
	private static final String FAIL_TOKEN = "获取新的token为空值！";
	private static final int SUCCESS_TOKEN_CODE = 0;
	private static final String SUCCESS_TOKEN = "成功获取token！";
	private static final String FAIL_CONN_RC = "融云服务器URL错误！";
	private static final String FAIL_GET_TOKEN = "无法获取融云Token！";
	private static final String FAIL_DISCONN_RC = "无法关闭融去连接！";
	private static final int PORTRAIT_WIDTH = 120;//头像宽度
	private static final String RC_CODETYPE = "UTF-8";
	
	
	/**
	 * 根据userId判断是否已经存在可用的token
	 * 如果已经存在且grabber == 0，直接返回token，如果grabber == 1，则强制获取新的Token
	 * 如果不存在，从融云服务器获取token保存到本地服务器，同时返回token
	 * @param req
	 * @param resp
	 * @return
	 * @throws UnsupportedEncodingException 
	 * @throws ApiException 
	 */
	@ResponseBody
	@RequestMapping(value = "/club/getToken.do", method = RequestMethod.POST)
	public JSONObject getToken(HttpServletRequest request, HttpServletResponse response) {
		WebUtils.setEncoding(request, response);
		
		JSONObject json = new JSONObject();
		String message = SUCCESS_TOKEN;
		int code = SUCCESS_TOKEN_CODE;
		String token = "";
		
		int grabber = WebUtils.paramInt(request, "grabber", 0);

		//判断用户是否登录
		User userLogin = userAuth.getUser(request, response);
		if(userLogin == null || userLogin.getUid() == 0L) {
			message = INVALID_USER;
			code = INVALID_USER_CODE;
			json.put("code", code);
			json.put("message", message);
			json.put("token", token);
			return json;
		}
		
		long userId = userLogin.getUid();
		if(!memberService.isClubMember(userId)) {
			message = NOT_CLUB_MEMBER;
			code = NOT_CLUB_MEMBER_CODE;
		} else {
			User user = userService.findUser(userId);
			token = user.getToken();
			if(token == null || "".equals(token) || token.length() == 0 || grabber == 1) {//需要重新获取token,并保存到本地服务器中,grabber == 1是强制获取新的Token
				String nikeName = user.getNickname();
				String portraitUri = WebUtils.face(userId, PORTRAIT_WIDTH);//得到头像的URL
				
				//得到配置文件中的代理信息、融云配置信息
				String proxyUrl = systemConfig.getProxyUrl();
				int proxyPort = Integer.parseInt(systemConfig.getProxyPort());
				String appKey = systemConfig.getAppKey();
				String appSecret = systemConfig.getAppSecret();
				String rongcloudAuthUrl = systemConfig.getRongcloudAuthUrl();
				
				//得到Token的值
				String tokenOjbect;
				try {
					tokenOjbect = TokenController.getToken(appKey, appSecret, proxyUrl, proxyPort, String.valueOf(userId), nikeName, portraitUri, rongcloudAuthUrl);
					JSONObject tokenJson = JSONObject.parseObject(tokenOjbect);
					token = StringUtils.defaultString(tokenJson.getString("token"));
				} catch (ApiException e) {
					log.error("fail to getToken!", e);
				}
				
				//成功响应，但是token的值为空
				if(token == null || token.length() == 0) {
					message = FAIL_TOKEN;
					code = FAIL_TOKEN_CODE;
				} else {//保存token
					user.setToken(token);
					geliDao.update(user);
				}
			}
		}
		
		//设置返回的Json内容
		json.put("code", code);
		json.put("message", message);
		json.put("token", token);
		
		return json;
	}
	
	/**
	 * @param appKey 从融云开发者平台申请的 AppKey
	 * @param appSecret 从融云开发者平台申请的 AppSecret
	 * @param userId 用户ID
	 * @param name	用户昵称
	 * @param portraitUri 用户头像URL
	 * @param proxyUrl 代理服务器IP
	 * @param proxyPort 代理用务器端口
	 * @returnString 
	 */
	public static String auth(String rongcloudAuthUrl, String appKey, String appSecret, String userId,
			String name, String portraitUri, String proxyUrl, int proxyPort) {
		StringBuilder retSb = null;
		HttpURLConnection conn = null;
		
		try {
			AUTH_URL = new URL(rongcloudAuthUrl);
		} catch (MalformedURLException e) {
			log.error(FAIL_CONN_RC);
		}
		
		try {
			//判断是否需要代理连接
			if(proxyUrl != null && proxyPort > 0 && !"".equals(proxyUrl)) {
				Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl, proxyPort));
				conn = (HttpURLConnection) AUTH_URL.openConnection(proxy);
			} else {
				conn = (HttpURLConnection) AUTH_URL.openConnection();
			}
			
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			HttpURLConnection.setFollowRedirects(true);
			conn.setInstanceFollowRedirects(true);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("appKey", appKey);
			conn.setRequestProperty("appSecret", appSecret);
			conn.setRequestProperty("Content-Type",
					"Application/x-www-form-urlencoded");
			StringBuilder sb = new StringBuilder("userId=");
			sb.append(URLEncoder.encode(userId, RC_CODETYPE));
			sb.append("&name=").append(URLEncoder.encode(name, RC_CODETYPE));
			sb.append("&portraitUri=").append(
					URLEncoder.encode(portraitUri, RC_CODETYPE));

			OutputStream out = conn.getOutputStream();
			out.write(sb.toString().getBytes(RC_CODETYPE));
			out.flush();
			out.close();
			
			if(conn.getResponseCode() == 200){
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						conn.getInputStream()));
	
				retSb = new StringBuilder();
				String line;
				while ((line = reader.readLine()) != null) {
					retSb.append(line);
				}
				reader.close();
			}else{
				log.error(FAIL_GET_TOKEN);
				return null;
			}
		} catch (Exception ignore) {
			log.error(FAIL_GET_TOKEN);
		} finally {
			try{
				conn.disconnect();
			}catch(Exception ignore){
				log.error(FAIL_DISCONN_RC);
			}
		}
		return retSb == null ? null : retSb.toString();
	}
	
	private static final String INVALID_CLUB = "车友会没有通过审核！";
	private static final int INVALID_CLUB_CODE = 1;
	private static final String SUCCESS_GET_FRIENDLIST = "成功获取车友会成员列表！";
	private static final int SUCCESS_GET_FRIENDLIST_CODE = 0;
	
	/**
	 * 每张图片的画布长度为150
	 * 根据图片的数量定义画布总长度
	 */
	private static final String CANVAS_WIDTH_234 = "org_330";//画布宽高（图片数为2，3，4）
	private static final String CANVAS_WIDTH_56789 = "org_490";//画布宽高（图片数>5）
	private static final String CANVAS_FINAL_WIDTH = "icon_96";//图片最终为96x96px
	private static final String CANVAS_URL = "http://imgw.pconline.com.cn/images/upload/spcgroup/face/";//获取图片的URL
	private static final String DEFAUL_IMAGES_URL_96x96 = "http://www1.pcauto.com.cn/app/autoclub/img/96x96.jpg";
	private static final String[] CANVAS_330_IMAGES_2 = {"10x90","170x90"};
	private static final String[] CANVAS_330_IMAGES_3 = {"90x10","10x170","170x170"};
	private static final String[] CANVAS_330_IMAGES_4 = {"10x10","170x10","10x170","170x170"};
	private static final String[] CANVAS_490_IMAGES_5 = {"90x90","250x90","10x250","170x250","330x250"};
	private static final String[] CANVAS_490_IMAGES_6 = {"10x90","170x90","330x90","10x250","170x250","330x250"};
	private static final String[] CANVAS_490_IMAGES_7 = {"10x10","170x10","330x10","10x170","170x170","330x170","10x330"};
	private static final String[] CANVAS_490_IMAGES_8 = {"10x10","170x10","330x10","10x170","170x170","330x170","10x330","170x330"};
	private static final String[] CANVAS_490_IMAGES_9 = {"10x10","170x10","330x10","10x170","170x170","330x170","10x330","170x330","330x330"};
	/**
	 * 根据车友会ID获取车友会成员信息
	 * @param request
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@ResponseBody
	@RequestMapping(value = "/club/getFriendList.do", method = RequestMethod.POST)
	public JSONObject getFriendList(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		WebUtils.setEncoding(request, response);
		String message;
		int code;
		List<ClubMember> listUsersForImage = new ArrayList<ClubMember>();//保存所有车友会成员信息，用于群图像
		
		JSONObject json = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		//获取车友会ID
		long clubId = WebUtils.paramLong(request, "clubId", 0L);
		
		//判断用户是否登录
		User userLogin = userAuth.getUser(request, response);
		if (userLogin == null || userLogin.getUid() == 0L) {
			AppUtils.setNoLoginCode(json);
			return json;
		}
		
		Club validClub = clubService.getValidClub(clubId);//通过ID获取状态为审核通过或被锁的车友会
		if(validClub == null) {//是否存在有效的车友会
			message = INVALID_CLUB;
			code = INVALID_CLUB_CODE;
		} else {
			List<User> listUsers = memberService.getUserByClubIdAndToken(clubId);//得到车友会成员列表用户详细信息（只有获取Token）
			listUsersForImage = memberService.listMemberByClubId(clubId);//得到车友会成员列表用户详细信息（全部）
			for(User user : listUsers) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("userId", user.getUid());
				jsonObject.put("userName", user.getNickname());
				jsonObject.put("faceUrl", WebUtils.face(user.getUid(), PORTRAIT_WIDTH));
				jsonArray.add(jsonObject);
			}
			message = SUCCESS_GET_FRIENDLIST;
			code = SUCCESS_GET_FRIENDLIST_CODE;
		}
		
		//根据朋友列表数获取群聊图片
		String image = "";
		String user_image = "";
		int friends = listUsersForImage.size();
		switch (friends) {//代表好友个数，至少要2个会员以上才有群图片，大于9人时只显示最早加入的9人头像组合图片
		case 0:
			break;
		case 1:
			image = DEFAUL_IMAGES_URL_96x96;//如果车友会只有一个会员时，群图片为默认图片
			break;
		case 2:
			for(int i=0; i< friends; i++) {
				if(i==(friends-1)) {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_330_IMAGES_2[i];
				} else {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_330_IMAGES_2[i]+",";
				}
			}
			image = CANVAS_URL+CANVAS_WIDTH_234+","+CANVAS_FINAL_WIDTH+","+user_image+".jpg";
			break;
		case 3:
			for(int i=0; i< friends; i++) {
				if(i==(friends-1)) {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_330_IMAGES_3[i];
				} else {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_330_IMAGES_3[i]+",";
				}
			}
			image = CANVAS_URL+CANVAS_WIDTH_234+","+CANVAS_FINAL_WIDTH+","+user_image+".jpg";
			break;
		case 4:
			for(int i=0; i< friends; i++) {
				if(i==(friends-1)) {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_330_IMAGES_4[i];
				} else {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_330_IMAGES_4[i]+",";
				}
			}
			image = CANVAS_URL+CANVAS_WIDTH_234+","+CANVAS_FINAL_WIDTH+","+user_image+".jpg";
			break;
		case 5:
			for(int i=0; i< friends; i++) {
				if(i==(friends-1)) {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_490_IMAGES_5[i];
				} else {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_490_IMAGES_5[i]+",";
				}
			}
			image = CANVAS_URL+CANVAS_WIDTH_56789+","+CANVAS_FINAL_WIDTH+","+user_image+".jpg";
			break;
		case 6:
			for(int i=0; i< friends; i++) {
				if(i==(friends-1)) {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_490_IMAGES_6[i];
				} else {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_490_IMAGES_6[i]+",";
				}
			}
			image = CANVAS_URL+CANVAS_WIDTH_56789+","+CANVAS_FINAL_WIDTH+","+user_image+".jpg";
			break;
		case 7:
			for(int i=0; i< friends; i++) {
				if(i==(friends-1)) {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_490_IMAGES_7[i];
				} else {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_490_IMAGES_7[i]+",";
				}
			}
			image = CANVAS_URL+CANVAS_WIDTH_56789+","+CANVAS_FINAL_WIDTH+","+user_image+".jpg";
			break;
		case 8:
			for(int i=0; i< friends; i++) {
				if(i==(friends-1)) {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_490_IMAGES_8[i];
				} else {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_490_IMAGES_8[i]+",";
				}
			}
			image = CANVAS_URL+CANVAS_WIDTH_56789+","+CANVAS_FINAL_WIDTH+","+user_image+".jpg";
			break;
		case 9:
			for(int i=0; i< friends; i++) {
				if(i==(friends-1)) {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_490_IMAGES_9[i];
				} else {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_490_IMAGES_9[i]+",";
				}
			}
			image = CANVAS_URL+CANVAS_WIDTH_56789+","+CANVAS_FINAL_WIDTH+","+user_image+".jpg";
			break;


		default://如果好友列表多于9人时，图片只显示最早加入车友会的9人图片组合
			for(int i=0; i< 9; i++) {
				if(i==8) {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_490_IMAGES_9[i];
				} else {
					user_image = user_image+listUsersForImage.get(i).getUid()+"_"+CANVAS_490_IMAGES_9[i]+",";
				}
			}
			image = CANVAS_URL+CANVAS_WIDTH_56789+","+CANVAS_FINAL_WIDTH+","+user_image+".jpg";
			break;
		}	
		
		//返回车友会成员列表
		json.put("code", code);
		json.put("message", message);
		json.put("image", image);
		json.put("friendList", jsonArray);
		
		return json;
	}
	
	//生成随机数
	private static final SecureRandom random = new SecureRandom();
	
	/**
	 * 申请加入融云群
	 * @param appKey
	 * @param appSecret
	 * @param proxyUrl
	 * @param proxyPort
	 * @param userId
	 * @param groupId
	 * @param groupName
	 * @param rongcloudJoinUrl
	 * @return
	 * @throws ApiException
	 */
	public static String join(String appKey, String appSecret, String proxyUrl, int proxyPort, String userId, String groupId, String groupName, String rongcloudJoinUrl) throws ApiException {
		
		StringBuilder sb = new StringBuilder("userId=");
		try{
			sb.append(URLEncoder.encode(userId, "UTF-8"));
			sb.append("&groupId=").append(URLEncoder.encode(groupId, "UTF-8"));
			sb.append("&groupName=").append(URLEncoder.encode(groupName, "UTF-8"));
		}catch(Exception ignore){}
		
		return doRongApiPost(appKey, appSecret, proxyUrl, proxyPort, rongcloudJoinUrl, sb.toString());
	}
	
	/**
	 * 申请退出融云群
	 * @param appKey
	 * @param appSecret
	 * @param proxyUrl
	 * @param proxyPort
	 * @param userId
	 * @param groupId
	 * @param rongcloudQuitUrl
	 * @return
	 * @throws ApiException
	 */
	public static String quit(String appKey, String appSecret, String proxyUrl, int proxyPort, String userId, String groupId, String rongcloudQuitUrl) throws ApiException {
		
		StringBuilder sb = new StringBuilder("userId=");
		try{
			sb.append(URLEncoder.encode(userId, "UTF-8"));
			sb.append("&groupId=").append(URLEncoder.encode(groupId, "UTF-8"));
		}catch(Exception ignore){}
		
		return doRongApiPost(appKey, appSecret, proxyUrl, proxyPort, rongcloudQuitUrl, sb.toString());
	}
	
	/**
	 * 申请解散融云群
	 * @param appKey
	 * @param appSecret
	 * @param proxyUrl
	 * @param proxyPort
	 * @param userId
	 * @param groupId
	 * @param rongcloudDismissUrl
	 * @return
	 * @throws ApiException
	 */
	public static String dismiss(String appKey, String appSecret, String proxyUrl, int proxyPort, String userId, String groupId, String rongcloudDismissUrl) throws ApiException {
		
		StringBuilder sb = new StringBuilder("userId=");
		try{
			sb.append(URLEncoder.encode(userId, "UTF-8"));
			sb.append("&groupId=").append(URLEncoder.encode(groupId, "UTF-8"));
		}catch(Exception ignore){}
		
		return doRongApiPost(appKey, appSecret, proxyUrl, proxyPort, rongcloudDismissUrl, sb.toString());
	}
	
	/**
	 * 获取融云Token
	 * @param appKey
	 * @param appSecret
	 * @param proxyUrl
	 * @param proxyPort
	 * @param userId
	 * @param name
	 * @param portraitUri
	 * @param getTokenUrl
	 * @return
	 * @throws ApiException
	 */
	public static String getToken(String appKey, String appSecret, String proxyUrl, int proxyPort, String userId, String name, String portraitUri, String getTokenUrl) throws ApiException {
		StringBuilder sb = new StringBuilder("userId=");
		try{
			sb.append(URLEncoder.encode(userId, "UTF-8"));
			sb.append("&name=").append(URLEncoder.encode(name, "UTF-8"));
			sb.append("&portraitUri=").append(URLEncoder.encode(portraitUri, "UTF-8"));
		}catch(Exception ignore){}
		
		return doRongApiPost(appKey, appSecret, proxyUrl, proxyPort, getTokenUrl, sb.toString());
	}
	
	/**
	 * 将字条串转换为SHA-1码
	 * @param value
	 * @return
	 */
	public static String hexSHA1(String value) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(value.getBytes("utf-8"));
			byte[] digest = md.digest();
			return byteToHexString(digest);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}
	
	/**
	 * 将字条串转换为SHA-1码（逻辑实现）
	 * @param bytes
	 * @return
	 */
	public static String byteToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();  
        for (int n = 0; n < bytes.length; n++) {  
            String stmp = Integer.toHexString(bytes[n] & 0xFF);
            sb.append((stmp.length() == 1) ? "0" + stmp : stmp);  
        }  
        return sb.toString().toUpperCase().trim();
	}
	
	/**
	 * 融云相关接口入口 
	 * @param appKey
	 * @param appSecret
	 * @param apiUrl
	 * @param postParams
	 * @return
	 * @throws ApiException
	 */
	private static String doRongApiPost(String appKey, String appSecret, String proxyUrl, int proxyPort, String apiUrl, String postParams) throws ApiException {
		StringBuilder retSb = null;
		HttpURLConnection conn = null;
		
		try {
			//判断是否需要代理连接
			if(proxyUrl != null && proxyPort > 0 && !"".equals(proxyUrl) ) {
				Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl, proxyPort));
				conn = (HttpURLConnection) new URL(apiUrl).openConnection(proxy);
			} else {
				conn = (HttpURLConnection) new URL(apiUrl).openConnection();
			}
			
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			HttpURLConnection.setFollowRedirects(true);
			conn.setInstanceFollowRedirects(true);
			conn.setRequestMethod("POST");
			
			String nonce = new DecimalFormat("000000").format(random.nextInt(100000));
			String timestamp = String.valueOf(System.currentTimeMillis());
			
			//签名=SHA-1（appSecret + 随机数 + 时间戳）
			StringBuilder toSign = new StringBuilder(appSecret).append(nonce).append(timestamp);
			
			conn.setRequestProperty("App-Key", appKey);
			conn.setRequestProperty("Timestamp", timestamp);
			conn.setRequestProperty("Nonce", nonce);
			conn.setRequestProperty("Signature", hexSHA1(toSign.toString()));
			
			conn.setRequestProperty("Content-Type",
					"Application/x-www-form-urlencoded");
			
			if(postParams != null){
				OutputStream out = conn.getOutputStream();
				out.write(postParams.getBytes("UTF-8"));
				out.flush();
				out.close();
			}
			
			if(conn.getResponseCode() == 200){
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						conn.getInputStream()));
	
				retSb = new StringBuilder();
				String line;
				while ((line = reader.readLine()) != null) {
					retSb.append(line);
				}
				reader.close();
			}else{
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						conn.getErrorStream()));
				
	
				retSb = new StringBuilder();
				String line;
				while ((line = reader.readLine()) != null) {
					retSb.append(line);
				}
				reader.close();
				throw new ApiException(conn.getResponseCode(), retSb == null ? null : retSb.toString(), null); 
			}
		} catch (Exception ex) {
			if(ex instanceof ApiException){
				throw (ApiException)ex;
			}else{
				throw new ApiException(502, ex.getMessage(), ex);
			}
		} finally {
			try{
			conn.disconnect();
			}catch(Exception ignore){}
		}
		return retSb == null ? null : retSb.toString();
	}
	
	/**
	 * 申请加入聊天群（业务逻辑）
	 * @param userId
	 * @param clubId
	 * @param clubName
	 * @return
	 * @throws ApiException
	 */
	public boolean joinClub(String userId, String clubId, String clubName) throws ApiException {
		//得到配置文件中的代理信息、融云配置信息
		String proxyUrl = systemConfig.getProxyUrl();
		int proxyPort = Integer.parseInt(systemConfig.getProxyPort());
		String appKey = systemConfig.getAppKey();
		String appSecret = systemConfig.getAppSecret();
		String rongcloudJoinUrl = systemConfig.getRongcloudJoinUrl();
		
		String string = join(appKey, appSecret, proxyUrl, proxyPort, userId, clubId, clubName, rongcloudJoinUrl);
		try {
			JSONObject jsonObject = JSONObject.parseObject(string);
			int code = jsonObject.getIntValue("code");
			if(code == 200) {
				//log.info("调用融云Join接口,成功操作 !");
				return true;
			} else if(code == 504) {
				log.error("调用融云Join接口,消息服务处理超时 !");
				return false;
			} else if(code == 502) {
				log.error("调用融云Join接口,消息服务不可用 !");
				return false;
			} else {
				log.error("调用融云Join接口,未知错误 !");
				return false;
			}
		} catch(Exception exception) {
			log.error("调用融云Join接口失败！", exception);
			return false;
		}
	}
	
	/**
	 * 申请退出聊天群（业务逻辑）
	 * @param userId
	 * @param clubId
	 * @return
	 * @throws ApiException
	 */
	public boolean QuitClub(String userId, String clubId) throws ApiException {
		//得到配置文件中的代理信息、融云配置信息
		String proxyUrl = systemConfig.getProxyUrl();
		int proxyPort = Integer.parseInt(systemConfig.getProxyPort());
		String appKey = systemConfig.getAppKey();
		String appSecret = systemConfig.getAppSecret();
		String rongcloudQuitUrl = systemConfig.getRongcloudQuitUrl();
		
		String string = quit(appKey, appSecret, proxyUrl, proxyPort, userId, clubId, rongcloudQuitUrl);
		try {
			JSONObject jsonObject = JSONObject.parseObject(string);
			int code = jsonObject.getIntValue("code");
			if(code == 200) {
				//log.info("调用融云Quit接口,成功操作 !");
				return true;
			} else if(code == 504){
				log.error("调用融云Quit接口,消息服务处理超时 !");
				return false;
			} else if(code == 502) {
				log.error("调用融云Quit接口,消息服务不可用 !");
				return false;
			} else {
				log.error("调用融云Quit接口,未知错误 !");
				return false;
			}
		} catch(Exception exception) {
			log.error("调用融云Quit接口失败！", exception);
			return false;
		}
	}
	
	/**
	 * 同步融云群(这个动作
	 * @param request
	 * @param response
	 * @return
	 * @throws ApiException
	 */
	@ResponseBody
	@RequestMapping(value = "/club/syncClub.do", method = RequestMethod.POST)
    public JSONObject syncClub(HttpServletRequest request, HttpServletResponse response) throws ApiException {
		List<String> list = this.getSyncClubList();
		for(String str : list) {
			String[] strArray = str.split(",");
			System.out.println(strArray[0] + "--" + strArray[1] + "--" + strArray[2]);
			boolean flag = this.syncClub(strArray[0], strArray[1], strArray[2]);
			System.out.println("########flag#######" + flag);
		}
		
		WebUtils.setEncoding(request, response);
		
		JSONObject json = new JSONObject();
		
		json.put("flag", "done");
		
		return json;
	}
	
	public boolean syncClub(String userId, String clubId, String clubName) throws ApiException {
		//得到配置文件中的代理信息、融云配置信息
		String proxyUrl = systemConfig.getProxyUrl();
		int proxyPort = Integer.parseInt(systemConfig.getProxyPort());
		String appKey = systemConfig.getAppKey();
		String appSecret = systemConfig.getAppSecret();
		String rongcloudQuitUrl = "https://api.cn.rong.io/group/sync.json";
		
		String string = sync(appKey, appSecret, proxyUrl, proxyPort, userId, clubId, rongcloudQuitUrl, clubName);
		try {
			JSONObject jsonObject = JSONObject.parseObject(string);
			int code = jsonObject.getIntValue("code");
			if(code == 200) {
				//log.info("调用融云Quit接口,成功操作 !");
				return true;
			} else if(code == 504){
				log.error("调用融云Quit接口,消息服务处理超时 !");
				return false;
			} else if(code == 502) {
				log.error("调用融云Quit接口,消息服务不可用 !");
				return false;
			} else {
				log.error("调用融云Quit接口,未知错误 !");
				return false;
			}
		} catch(Exception exception) {
			log.error("调用融云Quit接口失败！", exception);
			return false;
		}
	}
	
	public static String sync(String appKey, String appSecret, String proxyUrl, int proxyPort, String userId, String groupId, String rongcloudQuitUrl, String clubName) throws ApiException {
		
		StringBuilder sb = new StringBuilder("userId=");
		try{
			sb.append(URLEncoder.encode(userId, "UTF-8"));
			sb.append("&group[").append(groupId).append("]=").append(clubName);
		}catch(Exception ignore){}
		return doRongApiPost(appKey, appSecret, proxyUrl, proxyPort, rongcloudQuitUrl, sb.toString());
	}

	
	/**
	 * 需要同步的用户信息
	 * @return
	 */
	private List<String> getSyncClubList() {
		List<String> list = new ArrayList<String>();
		/*
		list.add("63145,11451,粤洋会");
		list.add("402159,1041,广东地平线自驾俱乐部");
		list.add("2004738,1111,江西车友会");
		list.add("6014902,1191,珠三角轩逸车友会");
		*/
		return list;
	}
}
